import fs from "fs";
import minimist from 'minimist';
import { execa } from "execa";

const args = minimist(process.argv.slice(2));
const formats = args.f || 'global'; // 指定打包后的方式: esm-bunlder global cjs
const sourcemap = args.s || false; // 指定打包后是否生产 sourceMap

const targets = fs.readdirSync("packages").filter((f) => {
  // 过滤掉文件
  if (!fs.statSync(`packages/${f}`).isDirectory()) {
    return false;
  }
  return true;
});

async function build(target) {
  // 执行命令 rollup -c --environment TARGET:reactivity,xxx:xxx,xxx:xxx
  const env = 'production';
  await execa(
    'rollup',
    [
      '-c', // --watch --config
      '--environment',
      [
        `TARGET:${target}`,
        `FORMATS:${formats}`,
        `NODE_ENV:${env}`,
        sourcemap ? `SOURCE_MAP:true` : ``
      ].filter(Boolean).join(',')
    ],
    { stdio: 'inherit' } // 该子进程在当前命令行输出
  )
}

function runParallel(targets, iteratorFn) {
  const res = [];
  for (const item of targets) {
    const p = iteratorFn(item); // 返回 promise
    res.push(p);
  }

  return Promise.all(res);
}

runParallel(targets, build).then(() => {
  console.log()
  console.log("Success")
  console.log()
});
